﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MesProjectWinform.Entity.Request;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.工序排序
{
    public partial class Form_ProcessItem : DevExpress.XtraEditors.XtraForm
    {
        // 分页相关变量
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalRecords = 0;
        private PaginationControl paginationControl;

        // 工序分类数据
        private List<ProcessclassModel> processClassList;
        private string selectedClassId = string.Empty;

        // 已选择的工序列表
        private List<ProcessItemModel> selectedProcesses = new List<ProcessItemModel>();

        // 返回结果的委托
        public delegate void ProcessSelectedHandler(List<ProcessItemModel> processes);
        public event ProcessSelectedHandler OnProcessSelected;

        public Form_ProcessItem()
        {
            InitializeComponent();
        }

        private void Form_ProcessItem_Load(object sender, EventArgs e)
        {
            // 初始化分页控件
            InitPaginationControl();

            // 加载工序分类
            LoadProcessClass();
            
            // 注册gridView1的双击事件
            gridView1.DoubleClick += GridView1_DoubleClick;
            
            // 注册选择行变更事件
            gridView1.SelectionChanged += GridView1_SelectionChanged;
        }

        /// <summary>
        /// 处理网格行选择变更事件
        /// </summary>
        private void GridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (view != null)
                {
                    // 清空已选择列表
                    selectedProcesses.Clear();
                    
                    // 获取所有选中的行
                    int[] selectedRows = view.GetSelectedRows();
                    foreach (int rowHandle in selectedRows)
                    {
                        if (rowHandle >= 0)
                        {
                            var model = view.GetRow(rowHandle) as ProcessManagModel;
                            if (model != null)
                            {
                                // 创建ProcessItemModel并添加到已选择列表
                                ProcessItemModel selectedProcess = new ProcessItemModel
                                {
                                    PMId = model.PMId,
                                    PMName = model.PMName,
                                    EmpId = model.EmpId,
                                    EMPName = model.EMPName,
                                    DepName = model.DepName,
                                    DepId = model.DepId
                                };
                                
                                selectedProcesses.Add(selectedProcess);
                            }
                        }
                    }
        }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("处理行选择事件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPaginationControl()
        {
            // 创建分页控件
            paginationControl = new PaginationControl();
            paginationControl.Dock = DockStyle.Fill;
            paginationControl.PageSize = pageSize;
            paginationControl.CurrentPage = currentPage;
            paginationControl.TotalRecords = totalRecords;

            // 注册分页事件
            paginationControl.PageChanged += PaginationControl_PageChanged;
            paginationControl.PageSizeChanged += PaginationControl_PageSizeChanged;

            // 添加到panelControl4
            panelControl4.Controls.Add(paginationControl);
        }

        /// <summary>
        /// 分页控件页码变更事件处理
        /// </summary>
        private void PaginationControl_PageChanged(object sender, PageChangedEventArgs e)
        {
            // 获取新的页码和每页记录数
            currentPage = e.CurrentPage;
            pageSize = e.PageSize;

            // 重新加载数据
            LoadProcessData();
        }

        /// <summary>
        /// 分页控件每页记录数变更事件处理
        /// </summary>
        private void PaginationControl_PageSizeChanged(object sender, PageSizeChangedEventArgs e)
        {
            // 获取新的页码和每页记录数
            currentPage = e.CurrentPage;
            pageSize = e.PageSize;

            // 重新加载数据
            LoadProcessData();
        }

        /// <summary>
        /// 加载工序分类数据
        /// </summary>
        private async void LoadProcessClass()
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                HttpClientHelper helper = new HttpClientHelper();
                // 调用API
                string json = helper.RequestUrlNew(RequestType.Get, "WareHouse/Processclass/GetProcessclass", null);
                ApiResult<List<ProcessclassModel>> result = JsonConvert.DeserializeObject<ApiResult<List<ProcessclassModel>>>(json);

                if (result.Code == ApiEnums.Success)
                {
                    processClassList = result.Data;

                    // 绑定到下拉框
                    cmbProcessClass.Properties.Items.Clear();
                    foreach (var item in processClassList)
                    {
                        cmbProcessClass.Properties.Items.Add(item.PCName);
                    }

                    // 如果有数据，选中第一项
                    if (processClassList.Count > 0)
                    {
                        cmbProcessClass.SelectedIndex = 0;
                    }
                }
                else
                {
                    XtraMessageBox.Show("加载工序分类数据失败：" + result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载工序分类数据异常：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 工序分类下拉框选择变更事件
        /// </summary>
        private void cmbProcessClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbProcessClass.SelectedIndex >= 0 && processClassList != null && processClassList.Count > 0)
            {
                // 获取选中的工序分类ID
                selectedClassId = processClassList[cmbProcessClass.SelectedIndex].PCId;

                // 重置分页
                currentPage = 1;
                if (paginationControl != null)
                {
                    paginationControl.CurrentPage = currentPage;
                }

                // 加载工序数据
                LoadProcessData();
            }
        }

        /// <summary>
        /// 加载工序数据
        /// </summary>
        private async void LoadProcessData()
        {
            try
            {
                // 禁用分页控件，防止重复操作
                if (paginationControl != null)
                {
                    paginationControl.Enabled = false;
                }

                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                HttpClientHelper helper = new HttpClientHelper();
                // 调用API
                string url = $"WareHouse/ProcessManag/GetProcessManagNew?pageNum={currentPage}&pageSize={pageSize}&QryID={selectedClassId}&QryName={TxtName.Text.Trim()}";
                string json = helper.RequestUrlNew(RequestType.Get, url, null);
                ApiPaging<List<ProcessManagModel>> result = JsonConvert.DeserializeObject<ApiPaging<List<ProcessManagModel>>>(json);

                if (result.Code == ApiEnums.Success)
                {
                  
                    // 更新数据网格
                    gridControl1.DataSource = result.Data;

                    // 更新分页控件
                    if (paginationControl != null)
                    {
                        totalRecords = result.TotalCount;
                        paginationControl.TotalRecords = totalRecords;
                        paginationControl.CurrentPage = currentPage;
                        paginationControl.PageSize = pageSize;
                    }

                }
                else
                {
                    XtraMessageBox.Show("加载工序数据失败：" + result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载工序数据异常：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;

                // 启用分页控件
                if (paginationControl != null)
                {
                    paginationControl.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 自定义绘制行号
        /// </summary>
        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        /// <summary>
        /// 处理网格视图的双击事件
        /// </summary>
        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                // 获取点击的坐标
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo((e as MouseEventArgs).Location);

                // 检查是否点击了行
                if (hitInfo.InRow)
                {
                    var model = view.GetRow(hitInfo.RowHandle) as ProcessManagModel;
                    // 获取选中的工序数据
                    ProcessItemModel selectedProcess = new ProcessItemModel(); //view.GetRow(hitInfo.RowHandle) as ProcessItemModel;
                    selectedProcess.PMId = model.PMId;
                    selectedProcess.PMName = model.PMName;
                    selectedProcess.EmpId = model.EmpId;
                    selectedProcess.EMPName = model.EMPName;
                    selectedProcess.DepName = model.DepName;
                    selectedProcess.DepId = model.DepId;
                    if (selectedProcess != null)
                    {
                        // 创建新列表并添加选中的工序
                        List<ProcessItemModel> selectedProcessList = new List<ProcessItemModel> { selectedProcess };
                        
                        // 触发选择完成事件
                        OnProcessSelected?.Invoke(selectedProcessList);
                        
                        // 关闭窗体
                        DialogResult = DialogResult.OK;
                        Close();
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("处理双击事件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
      
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (selectedProcesses.Count == 0)
            {
                XtraMessageBox.Show("请至少选择一个工序！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 触发选择完成事件
            OnProcessSelected?.Invoke(selectedProcesses);

            // 关闭窗体
            DialogResult = DialogResult.OK;
            Close();
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            LoadProcessData();
        }
    }

}